package servlet;

import model.Goods;
import util.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/GoodsAllServlet.do")
public class GoodsAllServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Goods> searchResults1 = AllQuery();

        HttpSession session = request.getSession();
        session.setAttribute("searchResults1", searchResults1);

        response.sendRedirect(request.getContextPath() + "/background1/admin/goodsManager.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    private List<Goods> AllQuery() {
        String SQL = "SELECT * FROM goods";
        List<Goods> goodsList = new ArrayList<>();
        JDBCUtil jdbcUtil = new JDBCUtil();
        ResultSet resultSet = null;

        try {
            resultSet = jdbcUtil.prepareQuery(SQL);

            while (resultSet != null && resultSet.next()) {
                int goods_id = resultSet.getInt("goods_id");
                int user_id = resultSet.getInt("user_id");
                String created_at = resultSet.getString("created_at");
                String goods_image = resultSet.getString("goods_image");
                String goods_info = resultSet.getString("goods_info");
                String goods_category = resultSet.getString("goods_category");
                double goods_price = resultSet.getDouble("goods_price");

                Goods goods = new Goods(goods_id, created_at, goods_image, goods_info, goods_category, user_id, goods_price);
                goodsList.add(goods);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("Error querying the database", e);
        } finally {
            try {
                if (resultSet != null) resultSet.close();
                jdbcUtil.closeConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return goodsList;
    }
}
